package oop.ex3.nameserver.actions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;

import oop.ex3.messages.FileMessage;
import oop.ex3.messages.MessageInterface;
import oop.ex3.messages.SimpleMessage;
import oop.ex3.messages.ValidHeaders;
import oop.ex3.messages.exception.InvalidHeaderException;

import oop.ex3.nameserver.NSContext;
import oop.ex3.sockets.ClientSocket;

public class SendFiles extends NsAction{
	
	
	public SendFiles(NSContext context){
		super(context);
		
	}

	@Override
	public boolean run(ClientSocket socket, MessageInterface msg) {
		Set<String> files = _context.getFiles();
		//TODO if no file exist- empty list or null?
		if (files.isEmpty()){
			try {
				socket.SendMessage(new SimpleMessage(ValidHeaders.ENDLIST));
				return true;
				//TODO think about this- what do you want to do if you cant send the message?
			} catch (IOException e) {
				return false;
			} catch (InvalidHeaderException e) {
				return false;
			}
		} else {
			try {
				for (String file: files){
					socket.SendMessage(new FileMessage(ValidHeaders.NSCONTAINFILE, 
							file));
				}	socket.SendMessage(new SimpleMessage(ValidHeaders.ENDLIST));
				//TODO think about this- what do you want to do if you cant send the message?
			} catch (IOException e) {
				return false;
			} catch (InvalidHeaderException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} return true;

		}
	}


}
